package com.the_last.service.impl;

import com.the_last.mapper.ReservationMapper;
import com.the_last.pojo.po.Reservation;
import com.the_last.service.*;
import com.the_last.utils.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class DashboardServiceImpl implements DashboardService {
    
    private final VenueService venueService;
    private final ProductService productService;
    private final OrderService orderService;
    private final ReservationService reservationService;
    private final ReservationMapper reservationMapper;
    
    @Override
    public Result getStatistics() {
        Map<String, Object> data = new HashMap<>();
        
        // 获取场馆数量（逻辑删除的会自动过滤）
        long venueCount = venueService.count();
        data.put("venueCount", venueCount);
        
        // 获取今日0点的Date对象
        LocalDateTime midnight = LocalDate.now().atStartOfDay();
        
        // 获取今日预约数（按场馆和日期分组）
        long todayReservationCount = reservationService.lambdaQuery()
                .gt(Reservation::getApplyTime, midnight).count();
        data.put("todayReservationCount", todayReservationCount);
        
        // 获取商品数量（逻辑删除的会自动过滤）
        long productCount = productService.count();
        data.put("productCount", productCount);
        
        // 获取订单总数（逻辑删除的会自动过滤）
        long orderCount = orderService.count();
        data.put("orderCount", orderCount);
        
        return Result.success(data);
    }
    
    @Override
    public Result getWeeklyReservations(String startDate, String endDate) {
        LocalDate mondayDate;
        LocalDate sundayDate;
        
        // 优先使用前端传递的明确开始和结束日期
        if (StringUtils.hasText(startDate) && StringUtils.hasText(endDate)) {
            mondayDate = LocalDate.parse(startDate);
            sundayDate = LocalDate.parse(endDate);
        } else {
            return Result.fail("请提供开始和结束日期");
        }
        
        // 传递预处理后的日期给SQL
        List<Integer> weeklyData = reservationMapper.getWeeklyReservationCounts(
                mondayDate.toString(),
                sundayDate.toString()
        );
        
        return Result.success(weeklyData);
    }
}